package com.yzp.service.impl;

import com.yzp.dao.UserDao;
import com.yzp.entity.User;
import com.yzp.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.*;
import java.util.List;

/**
 * @title: UserServiceImpl
 * @Author: yzp
 * @Date: 2019/7/22 16:49
 * @Version 1.0
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;


    @Override
    public List<User> findAll() {
        List<User> all = userDao.findAll();
        return all;
    }

    @Override
    public User findOne(Long id) {
    /*  Specification<User> specification = new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Path<Object> uid = root.get("id");
                Predicate predicate = criteriaBuilder.equal(uid, id);
                return predicate;
            }
        };
        Optional<User> optional = userDao.findOne(specification);
        User user1 = optional.get();*/
        User user = userDao.getOne(id);
        return user;
    }

    @Override
    public User findByName(String name) {
        return userDao.findByUsername(name);
    }

    @Override
    public List<User> findByJPQL(String name, Long id) {
        return userDao.findJPQL(name, id);
    }

    @Override
    public Page findByPage(String name, Integer page, Integer size) {
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        PageRequest of = PageRequest.of(page - 1, size,sort);
        Specification<User> specification = new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Path<Object> userName = root.get("username");
                Predicate predicate = criteriaBuilder.like(userName.as(String.class), "%" + name + "%");
                return predicate;
            }
        };
        return userDao.findAll(specification, of);
    }
    @Override
    public void save(User user) {
        userDao.save(user);
    }

}
